//jqGrid的配置信息
$.jgrid.defaults.width = 1000;
$.jgrid.defaults.responsive = true;
$.jgrid.defaults.styleUI = 'Bootstrap';

var baseURL = "../../";

function apiurl(a){
	return baseURL + a;
}

function apiget(){
	var args = [].slice.apply(arguments);
	args[0] = baseURL + args[0];
	return $.get.apply(null,args);
}
function apipost(){
	var args = [].slice.apply(arguments);
	args[0] = baseURL + args[0];
	return $.post.apply(null,args);
}
function postjson(url,data,cbSuccess,cbError){
	return $.ajax({
		type : 'POST',
		url : baseURL + url,
		contentType: "application/json; charset=utf-8",
		data: JSON.stringify(data),
		success: function (res) {
			cbSuccess && cbSuccess.call(this,res);
		},
		error: function (err) {
			cbError && cbError.call(this,res);
		}
	})
}

//工具集合Tools
window.T = {
	grid : {
		appearance : {
			rowNum : 25
		}
	}
};

// 获取请求参数
// 使用示例
// location.href = http://localhost:8080/index.html?id=123
// T.p('id') --> 123;
T.p = function(name) {
	var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if(r!=null)return  unescape(r[2]); return null;
}

T.loading = function (isOpen){
	if(!isOpen){
		parent.layer.closeAll();
	}
	else{
		parent.layer.msg('加载中', {
			icon: 16
			,shade: 0.01
		});
	}
}

var str_format = T.format = function(){
	var  args  = [].slice.call(arguments);
	var str = args.shift();
	return   str.replace(/\{(\d+)\}/g, function (m,i,o,n) {
		return args[i];
	});
}

//全局配置
$.ajaxSetup({
	dataType: "json",
	cache: false
});

//重写alert
window.alert = function(msg, callback){
	parent.layer.alert(msg, function(index){
		parent.layer.close(index);
		if(typeof(callback) === "function"){
			callback("ok");
		}
	});
}

//重写confirm式样框
window.confirm = function(msg, callback){
	parent.layer.confirm(msg, {btn: ['确定','取消']},
	function(){//确定事件
		if(typeof(callback) === "function"){
			callback("ok");
		}
	});
}

function get_date_diff_string(startTime, endTime) {
	var retValue = {};
	if(/^\d+$/.test(startTime)){
		startTime = new Date(startTime*1000);
	}
	if(/^\d+$/.test(endTime)){
		endTime = new Date(endTime*1000);
	}
	var date3 = endTime.getTime() - startTime.getTime();  //时间差的毫秒数

	//计算出相差天数
	var days = Math.floor(date3 / (24 * 3600 * 1000));
	retValue.Days = days;

	var years = Math.floor(days / 365);
	retValue.Years = years;

	var months = Math.floor(days / 30);
	retValue.Months = months;

	//计算出小时数
	var leave1 = date3 % (24 * 3600 * 1000);    //计算天数后剩余的毫秒数
	var hours = Math.floor(leave1 / (3600 * 1000));
	retValue.Hours = hours;

	//计算相差分钟数
	var leave2 = leave1 % (3600 * 1000);        //计算小时数后剩余的毫秒数
	var minutes = Math.floor(leave2 / (60 * 1000));
	retValue.Minutes = minutes;

	//计算相差秒数
	var leave3 = leave2 % (60 * 1000);      //计算分钟数后剩余的毫秒数
	var seconds = Math.round(leave3 / 1000);
	retValue.Seconds = seconds;

	var strTime = "";
	if (years >= 1) {
		strTime = years + "年前";
	} else if (months >= 1) {
		strTime = months + "个月前";
	} else if (days >= 1) {
		strTime = days + "天前";
	} else if (hours >= 1) {
		strTime = hours + "小时前";
	} else {
		strTime = minutes + "分钟前";
	}
	retValue.PubTime = strTime;     //帖子,文章,博客发表时间的一种简短表示方法
	return retValue;
}

//选择一条记录
function getSelectedRow() {
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if(!rowKey){
    	alert("请选择一条记录");
    	return ;
    }
    
    var selectedIDs = grid.getGridParam("selarrrow");
    if(selectedIDs.length > 1){
    	alert("只能选择一条记录");
    	return ;
    }
    
    return selectedIDs[0];
}

//选择多条记录
function getSelectedRows() {
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if(!rowKey){
    	alert("请选择一条记录");
    	return ;
    }
    
    return grid.getGridParam("selarrrow");
}

//判断是否为空
function isBlank(value) {
    return !value || !/\S/.test(value)
}
//时间戳毫秒ms
function timestampForMS(cellvalue, options, rowObject) {
	if(cellvalue === undefined||cellvalue === null||cellvalue === ''){
		return ''
	}
	return moment(new Date(1000*cellvalue)).format("YYYY-MM-DD HH:mm:ss")
}
//时间戳秒s
function timestampForS(cellvalue, options, rowObject) {
	if(cellvalue === undefined||cellvalue === null||cellvalue === ''){
		return ''
	}
	return moment(new Date(cellvalue)).format("YYYY-MM-DD HH:mm:ss")
}

function set_gender_formatter(cellValue, options, rowData) {
	return str_format('');
	if(cellValue==1) return str_format('<i class="label label-info">男</i>');
	if(cellValue==0) return str_format('<i class="label label-danger">女</i>');
	if(cellValue==null ) return str_format("", cellValue);
}

function set_filesize_formatter(cellValue, options, rowData) {
	var value = parseInt(cellValue);
	if(null==value||value==''){
		return "0 Bytes";
	}
	var unitArr = new Array("Bytes","KB","MB","GB","TB","PB","EB","ZB","YB");
	var index=0;
	var srcsize = parseFloat(value);
	index=Math.floor(Math.log(srcsize)/Math.log(1024));
	var size =srcsize/Math.pow(1024,index);
	size=size.toFixed(2);//保留的小数位数
	return size+unitArr[index];
}

function set_images_formatter(cellValue, options, rowData) {
	if(cellValue==null||cellValue=='undefined'||cellValue==''){
		return str_format("", cellValue);
	}
	return str_format('<img src="{0}" class="row-image"/>', cellValue);
}


function dateFormat(date,fmt) {
	var ret;
	if(!fmt){
		fmt = 'yyyy-MM-dd HH:mm:SS';
	}
	const opt = {
		"y+": date.getFullYear().toString(),        // 年
		"M+": (date.getMonth() + 1).toString(),     // 月
		"d+": date.getDate().toString(),            // 日
		"H+": date.getHours().toString(),           // 时
		"m+": date.getMinutes().toString(),         // 分
		"S+": date.getSeconds().toString()          // 秒
		// 有其他格式化字符需求可以继续添加，必须转化成字符串
	};
	for (let k in opt) {
		ret = new RegExp("(" + k + ")").exec(fmt);
		if (ret) {
			fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
		}
	}
	return fmt;
}

var timestampFormat = function (timestamp, formats) {
	timestamp = timestamp * 1000
	var date = timestamp? new Date(timestamp): new Date();
	return dateFormat(date,formats);
};

var get_grid_column_formatter = function(key){
	return get_grid_column_formatter.formatters[key] ? get_grid_column_formatter.formatters[key] : undefined;
}

var set_grid_column_formatter = function(key,func){
	get_grid_column_formatter.formatters[key] = func;
}

get_grid_column_formatter.formatters = {};

$(function () {
	$.extend($.jgrid.defaults, {
		loadComplete: function(data){
			var args = [].slice.call(arguments);
			console.log(args);
			if(data.code < 0){
				layer.msg(data.msg);
			}
		},
		loadError: function(xhr,status,error){
			console.log(this);
			console.log([xhr,status,error])
		}
	});
})
//获取请求参数
String.prototype.getParameter = function (key) {
	var re = new RegExp(key + '=([^&]*)(?:&)?');
	return this.match(re) && this.match(re)[1];
};
